package com.bear.atlassianmcp.jira.mcp.tools;

import com.bear.atlassianmcp.jira.model.JiraIssue;
import com.bear.atlassianmcp.jira.model.request.CreateIssueRequest;
import com.bear.atlassianmcp.jira.service.JiraService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Issue管理MCP工具
 * 提供Issue的创建、查询、更新、评论等功能
 */
@Service
public class IssueTools {

    private static final Logger logger = LoggerFactory.getLogger(IssueTools.class);

    private final JiraService jiraService;

    @Autowired
    public IssueTools(JiraService jiraService) {
        this.jiraService = jiraService;
    }

    /**
     * 获取Issue详情
     *
     * @param issueKey Issue键值，如"PROJ-123"
     * @param context 工具上下文
     * @return Issue的详细信息，格式化为AI友好的文本
     */
    @Tool(description = "获取Jira Issue的详细信息，包括标题、状态、描述、经办人等所有字段")
    public String getIssue(@ToolParam(description = "Issue键值，格式如PROJ-123，其中PROJ是项目键，123是Issue编号") String issueKey, ToolContext context) {
        logger.info("MCP Tool: Getting issue {}", issueKey);

        try {
            JiraIssue issue = jiraService.getIssue(issueKey, context);
            String result = issue.toFormattedString();

            logger.debug("Successfully retrieved issue {} via MCP", issueKey);
            return result;

        } catch (Exception e) {
            logger.error("Failed to get issue {} via MCP: {}", issueKey, e.getMessage());
            return "错误：无法获取Issue " + issueKey + "。原因：" + e.getMessage();
        }
    }

    /**
     * 创建新Issue
     *
     * @param projectKey 项目键值，如"PROJ"
     * @param summary Issue标题
     * @param description Issue描述
     * @param issueType Issue类型，如"Task"、"Bug"、"Story"等
     * @param context 工具上下文
     * @return 创建结果信息
     */
    @Tool(description = "在指定项目中创建新的Jira Issue，需要提供项目键、标题、描述和Issue类型")
    public String createIssue(@ToolParam(description = "项目键值，如PROJ、DEMO等，可通过getProjects工具获取") String projectKey,
                             @ToolParam(description = "Issue标题，简洁描述问题或任务") String summary,
                             @ToolParam(description = "Issue详细描述，可以包含问题详情、需求说明等") String description,
                             @ToolParam(description = "Issue类型，如Task、Bug、Story、Epic等，具体类型取决于项目配置") String issueType,
                             @ToolParam(description = "处理人/经办人") String assignee,
                             @ToolParam(description = "优先级") String priority,
                             ToolContext context) {
        logger.info("MCP Tool: Creating issue in project {} with type {}", projectKey, issueType);

        try {
            CreateIssueRequest request = new CreateIssueRequest()
                .project(projectKey)
                .summary(summary)
                .description(description)
                .issueType(issueType)
                .assignee(assignee)
                .priority(priority);

            JiraIssue createdIssue = jiraService.createIssue(request, context);

            String result = String.format(
                "✅ 成功创建Issue！\n" +
                "Issue键值: %s\n" +
                "标题: %s\n" +
                "项目: %s\n" +
                "类型: %s\n" +
                "状态: %s\n" +
                "链接: %s/browse/%s",
                createdIssue.getKey(),
                createdIssue.getSummary(),
                createdIssue.getProject(),
                createdIssue.getIssueType(),
                createdIssue.getStatus(),
                jiraService.getApiBaseUrl().replace("/rest/api/2", ""),
                createdIssue.getKey()
            );

            logger.info("Successfully created issue {} via MCP", createdIssue.getKey());
            return result;

        } catch (Exception e) {
            logger.error("Failed to create issue via MCP: {}", e.getMessage());
            return "❌ 创建Issue失败。原因：" + e.getMessage();
        }
    }

    /**
     * 更新Issue字段
     *
     * @param issueKey Issue键值
     * @param field 要更新的字段名，如"summary"、"description"、"priority"等
     * @param value 新的字段值
     * @param context 工具上下文
     * @return 更新结果信息
     */
    @Tool(description = "更新Jira Issue的指定字段，常用字段包括summary(标题)、description(描述)、priority(优先级)等")
    public String updateIssue(@ToolParam(description = "Issue键值，格式如PROJ-123") String issueKey,
                             @ToolParam(description = "要更新的字段名，如summary、description、priority、assignee等") String field,
                             @ToolParam(description = "新的字段值，根据字段类型提供相应格式的值") String value,
                             ToolContext context) {
        logger.info("MCP Tool: Updating issue {} field {} to {}", issueKey, field, value);

        try {
            String result = jiraService.updateIssue(issueKey, field, value, context);

            logger.info("Successfully updated issue {} via MCP", issueKey);
            return "✅ " + result;

        } catch (Exception e) {
            logger.error("Failed to update issue {} via MCP: {}", issueKey, e.getMessage());
            return "❌ 更新Issue失败。原因：" + e.getMessage();
        }
    }

    /**
     * 为Issue添加评论
     *
     * @param issueKey Issue键值
     * @param comment 评论内容
     * @param context 工具上下文
     * @return 添加评论的结果信息
     */
    @Tool(description = "为Jira Issue添加评论，支持Markdown格式和@用户提及")
    public String addComment(@ToolParam(description = "Issue键值，格式如PROJ-123") String issueKey,
                            @ToolParam(description = "评论内容，支持Markdown格式，可以使用@username提及用户") String comment,
                            ToolContext context) {
        logger.info("MCP Tool: Adding comment to issue {}", issueKey);

        try {
            String result = jiraService.addComment(issueKey, comment, context);

            String response = String.format(
                "✅ 成功添加评论到Issue %s\n" +
                "评论内容: %s\n" +
                "时间: %s",
                issueKey,
                comment.length() > 100 ? comment.substring(0, 100) + "..." : comment,
                java.time.LocalDateTime.now().toString()
            );

            logger.info("Successfully added comment to issue {} via MCP", issueKey);
            return response;

        } catch (Exception e) {
            logger.error("Failed to add comment to issue {} via MCP: {}", issueKey, e.getMessage());
            return "❌ 添加评论失败。原因：" + e.getMessage();
        }
    }

    /**
     * 创建带优先级的Issue
     * 
     * @param projectKey 项目键值
     * @param summary Issue标题
     * @param description Issue描述
     * @param issueType Issue类型
     * @param priority 优先级，如"High"、"Medium"、"Low"
     * @return 创建结果信息
     */
    // @Tool(description = "创建带有指定优先级的Jira Issue，优先级可以是High、Medium、Low等")
    public String createIssueWithPriority(String projectKey, String summary, String description, 
                                         String issueType, String priority, ToolContext context) {
        logger.info("MCP Tool: Creating issue with priority {} in project {}", priority, projectKey);
        
        try {
            CreateIssueRequest request = new CreateIssueRequest()
                .project(projectKey)
                .summary(summary)
                .description(description)
                .issueType(issueType)
                .priority(priority);
            
            JiraIssue createdIssue = jiraService.createIssue(request, context);
            
            String result = String.format(
                "✅ 成功创建高优先级Issue！\n" +
                "Issue键值: %s\n" +
                "标题: %s\n" +
                "项目: %s\n" +
                "类型: %s\n" +
                "优先级: %s\n" +
                "状态: %s\n" +
                "链接: %s/browse/%s",
                createdIssue.getKey(),
                createdIssue.getSummary(),
                createdIssue.getProject(),
                createdIssue.getIssueType(),
                createdIssue.getPriority(),
                createdIssue.getStatus(),
                jiraService.getApiBaseUrl().replace("/rest/api/2", ""),
                createdIssue.getKey()
            );
            
            logger.info("Successfully created issue {} with priority {} via MCP", 
                       createdIssue.getKey(), priority);
            return result;
            
        } catch (Exception e) {
            logger.error("Failed to create issue with priority via MCP: {}", e.getMessage());
            return "❌ 创建Issue失败。原因：" + e.getMessage();
        }
    }

    /**
     * 批量更新Issue的多个字段
     * 
     * @param issueKey Issue键值
     * @param summary 新标题（可选，传null跳过）
     * @param description 新描述（可选，传null跳过）
     * @param priority 新优先级（可选，传null跳过）
     * @return 更新结果信息
     */
    @Tool(description = "批量更新Jira Issue的多个字段，包括标题、描述、优先级等，不需要更新的字段可以传null")
    public String updateIssueFields(@ToolParam(description = "Issue键值，格式如PROJ-123") String issueKey,
                                   @ToolParam(required = false, description = "新标题，如果不需要更新可以传null") String summary,
                                   @ToolParam(required = false, description = "新描述，如果不需要更新可以传null") String description,
                                   @ToolParam(required = false, description = "新优先级，如High、Medium、Low等，如果不需要更新可以传null") String priority,
                                   ToolContext context) {
        logger.info("MCP Tool: Batch updating issue {}", issueKey);
        
        try {
            StringBuilder results = new StringBuilder();
            results.append("✅ Issue ").append(issueKey).append(" 批量更新结果：\n");
            
            if (summary != null && !summary.trim().isEmpty()) {
                jiraService.updateIssue(issueKey, "summary", summary, context);
                results.append("- 标题已更新\n");
            }
            
            if (description != null && !description.trim().isEmpty()) {
                jiraService.updateIssue(issueKey, "description", description,context);
                results.append("- 描述已更新\n");
            }
            
            if (priority != null && !priority.trim().isEmpty()) {
                jiraService.updateIssue(issueKey, "priority", priority, context);
                results.append("- 优先级已更新为: ").append(priority).append("\n");
            }
            
            results.append("更新时间: ").append(java.time.LocalDateTime.now());
            
            logger.info("Successfully batch updated issue {} via MCP", issueKey);
            return results.toString();
            
        } catch (Exception e) {
            logger.error("Failed to batch update issue {} via MCP: {}", issueKey, e.getMessage());
            return "❌ 批量更新Issue失败。原因：" + e.getMessage();
        }
    }
}
